import { getCarouselList, type CarouselItem } from '@/services/CarouselService';
import { getDynamicLatest, type DynamicInfo } from '@/services/DynamicService';
import { ArrowRightOutlined, CalendarOutlined } from '@ant-design/icons';
import zhCN from 'antd/es/locale/zh_CN';
import { Button, Card, Carousel, Col, Row, Statistic, Typography, Image, ConfigProvider, message, Empty } from 'antd';
import { history } from '@umijs/max';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { famousPersonId } from '@/services';
import { FileDetail } from '@/services';
import dayjs from 'dayjs';
import { getLatestActivities, type ActivityInfo } from '@/services/ActivityService';

const { Title } = Typography;
const { Countdown } = Statistic;

const HomePage: React.FC = () => {
  const [carouselItems, setCarouselItems] = useState<CarouselItem[]>([]);
  const [latestNews, setLatestNews] = useState<DynamicInfo[]>([]);
  const [activities, setActivities] = useState<ActivityInfo[]>([]);

  // 获取轮播图数据
  useEffect(() => {
    const fetchCarouselData = async () => {
      try {
        const list = await getCarouselList();
        console.log(list);
        setCarouselItems(list);
      } catch (error) {
        console.error('获取轮播图数据失败：', error);
      }
    };

    fetchCarouselData();
  }, []);

  // 获取最新动态
  useEffect(() => {
    const fetchLatestNews = async () => {
      try {
        const data = await getDynamicLatest(famousPersonId);
        setLatestNews(data);
      } catch (error) {
        console.error('获取最新动态失败：', error);
      }
    };

    fetchLatestNews();
  }, []);

  // 获取最新活动
  useEffect(() => {
    const fetchActivities = async () => {
      try {
        const data = await getLatestActivities(famousPersonId);
        console.log(data);
        setActivities(data);
      } catch (error) {
        console.error('获取活动列表失败：', error);
      }
    };

    fetchActivities();
  }, []);

  // 处理动态卡片点击
  const handleDynamicClick = (id: number) => {
    history.push(`/dynamic/${btoa(id.toString())}`);
  };

  // 格式化时间戳
  const formatDate = (timestamp: string) => {
    return dayjs(parseInt(timestamp)).format('YYYY-MM-DD HH:mm');
  };

  const renderMediaGrid = (imageList: FileDetail[] = [], videoList: FileDetail[] = []) => {
    if (imageList?.length === 0 && videoList?.length === 0) return null;

    const getLayoutClass = (total: number) => {
      switch(total) {
        case 1: return styles.singleMedia;
        case 2: return styles.doubleMedia;
        case 3: return styles.tripleMedia;
        case 4: return styles.quadMedia;
        default: return styles.multiMedia;
      }
    };

    // 处理图片显示
    const displayCount = Math.min(imageList?.length || 0, 9);
    const remainingImages = (imageList?.length || 0) - displayCount;

    return (
      <div 
        className={`${styles.mediaGrid} ${getLayoutClass(displayCount)}`}
        onClick={(e) => e.stopPropagation()}
      >
        <Image.PreviewGroup>
          {imageList?.slice(0, displayCount).map((image, index) => (
            <div key={image.id} className={styles.mediaWrapper}>
              <div className={styles.imageItem}>
                <Image
                  src={`/api/file/play/${image.id}`}
                  alt=""
                />
                {/* 在最后一张图片上显示剩余数量 */}
                {index === displayCount - 1 && remainingImages > 0 && (
                  <div className={styles.moreOverlay}>
                    +{remainingImages}
                  </div>
                )}
              </div>
            </div>
          ))}
        </Image.PreviewGroup>
        {/* 如果有视频,显示视频数量提示 */}
        {/* {videoList?.length > 0 && (
          <div className={styles.videoCount}>
            <PlayCircleOutlined /> 含{videoList.length}个视频
          </div>
        )} */}
      </div>
    );
  };

  // 处理活动报名
  const handleSignup = () => {
    // TODO: 实现报名功能
    message.info('报名功能开发中');
  };

  return (
    <ConfigProvider locale={zhCN}>
    <div className={styles.container}>
      {/* 轮播图部分 */}
      <Carousel
        autoplay
        className={styles.carousel}
        effect="fade"
        autoplaySpeed={5000}
      >
        {carouselItems.map((item) => (
          <div key={item.id}>
            <div className={styles.carouselItem}>
              <div
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  backgroundImage: `url(/api/file/play/${item.imageId})`,
                  backgroundSize: 'cover',
                  backgroundPosition: 'center',
                }}
              />
              <div className={styles.carouselContent}>
                <h2>{item.title}</h2>
                {item.description && <p>{item.description}</p>}
                <Button
                  type="primary"
                  size="large"
                  onClick={() => window.open(item.linkUrl, '_blank')}
                >
                  了解更多
                </Button>
              </div>
            </div>
          </div>
        ))}
      </Carousel>

      {/* 最新动态部分 */}
      <div className={styles.section}>
        <div className={styles.sectionHeader}>
          <Title level={2}>最新动态</Title>
          <Button 
            type="link" 
            icon={<ArrowRightOutlined />} 
            onClick={() => history.push('/dynamic')}
          >
            查看更多
          </Button>
        </div>
        <Row gutter={[24, 24]}>
          {latestNews.length > 0 ? (
            latestNews.map((item) => (
              <Col xs={24} sm={12} key={item.id}>
                <Card 
                  className={styles.dynamicCard}
                  bordered={false}
                  onClick={() => handleDynamicClick(item.id!)}
                >
                  <div className={styles.dynamicContent}>
                    <h3 className={styles.title}>{item.title}</h3>
                    <div className={styles.time}>
                      <CalendarOutlined /> {formatDate(item.date)}
                    </div>
                    <div className={styles.text}>{item.content}</div>
                    {renderMediaGrid(item.imageList, item.videoList)}
                  </div>
                </Card>
              </Col>
            ))
          ) : (
            <Col span={24}>
              <Card bordered={false}>
                <Empty description="暂无最新动态" />
              </Card>
            </Col>
          )}
        </Row>
      </div>

      {/* 近期活动部分 */}
      {/* <div className={styles.section}>
        <div className={styles.sectionHeader}>
          <Title level={2}>近期活动</Title>
          <Button 
            type="link" 
            icon={<ArrowRightOutlined />} 
            onClick={() => history.push('/activity')}
          >
            查看更多
          </Button>
        </div>
        <Row gutter={[24, 24]}>
          {activities.length > 0 ? (
            activities.map((activity) => (
              <Col xs={24} md={12} key={activity.id}>
                <Card 
                  className={styles.eventCard}
                  onClick={() => history.push(`/activity/${btoa(activity.id!.toString())}`)}
                >
                  <div className={styles.eventInfo}>
                    <h3>{activity.title}</h3>
                    <p>
                      <CalendarOutlined /> {dayjs(activity.startTime).format('YYYY-MM-DD HH:mm')}
                    </p>
                    {activity.location && (
                      <p className={styles.location}>{activity.location}</p>
                    )}
                    <p className={styles.description}>{activity.description}</p>
                  </div>
                  <div className={styles.eventCountdown}>
                    <Countdown
                      title="距离开始还有"
                      value={dayjs(activity.startTime).valueOf()}
                      format="D 天 H 时 m 分"
                    />
                    <Button 
                      type="primary" 
                      className={styles.signupBtn}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleSignup(activity.id!);
                      }}
                      disabled={dayjs().isAfter(dayjs(activity.registrationDeadline))}
                    >
                      {dayjs().isAfter(dayjs(activity.registrationDeadline)) 
                        ? '报名已截止' 
                        : '立即报名'
                      }
                    </Button>
                  </div>
                </Card>
              </Col>
            ))
          ) : (
            <Col span={24}>
              <Card bordered={false}>
                <Empty description="暂无近期活动" />
              </Card>
            </Col>
          )}
        </Row>
      </div> */}
    </div>
    </ConfigProvider>
  );
};

export default HomePage;
